package com.mirabelle.juice.controller;

import java.io.Serializable;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.mirabelle.juice.beans.UserDetailsImpl;
import com.mirabelle.juice.model.Author;
import com.mirabelle.juice.service.AuthorService;

@Controller("C_LOGGED_AUTHOR")
@Scope("session")
public class CPreferences implements Serializable {
	private static final long	serialVersionUID	= 1L;
	private transient Logger	log					= LoggerFactory.getLogger(getClass());

	private Author		loggedAuthor			= null;
	private String 		locale					= "fr";
	
	@Autowired
	@Qualifier("AuthorService")
	protected AuthorService	authorService;
	
	@PostConstruct
	public void init() {
		log.debug("Initialisation du controlleur C_LOGGED_AUTHOR.");
	}
	
	public void reload() {
		if (null != loggedAuthor) {
			authorService.reload(loggedAuthor);
		}
	}
	
	public Author getLoggedAuthor() {
		//log.debug("Recherche de l'utilisateur authentifié en cache");
		if (null == loggedAuthor) {
			log.debug("L'utilisateur authentifié n'existe pas encore, recherche dans le contexte de securité spring.");
			if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof String) {
				log.debug("Aucun utilisateur authentifié.");
			} else {
				UserDetailsImpl user = null;
				try {
					user = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
				} catch (ClassCastException e) {
					log.error("Erreur dans la recherche de l'utilisateur authentifié.", e);
				}
				log.debug("Utilisateur authentifié trouvé: " + user.getUsername());
				try {
					loggedAuthor = authorService.findAuthorByUniqueIdentifier(user.getUsername());
				} catch (Exception e) {
					
				}
				log.debug(
						"Utilisateur authentifié : " 
						+ loggedAuthor 
						+ "[Nickname = " + loggedAuthor.getNickName()
						+ " Mail = " + loggedAuthor.getMail()
						+ " FirstName = " + loggedAuthor.getFirstName()
						+ " LastName = " + loggedAuthor.getLastName()
						+ " isAdmin = " + loggedAuthor.getAdmin()
						+ "]");
			}
		}
		return loggedAuthor;
	}

	public String getLocale() {
		return locale;
	}

	public void setLocale(String locale) {
		log.debug("Reglage de la locale depuis " + this.locale + " vers " + locale);
		this.locale = locale;
	}

}
